using System;
using UnityEngine;

public class PachinkoBall : MonoBehaviour
{
    public bool isStarted = false;
    private Animator anim;
    private Rigidbody2D _rigidbody2D;
    
    public float speed = 5.0f;
    public Vector2 force;
    
    // Start is called before the first frame update
    void Start()
    {
        anim = GetComponent<Animator>();
        _rigidbody2D = GetComponent<Rigidbody2D>();
            
        transform.position = Vector3.up * 1.5f;

        Invoke("Init", .5f);
    }

    // void DelayRun()
    // {
    //     _rigidbody2D.AddForce(force);
    //     isStarted = true;
    // }

    // Update is called once per frame
    void Update()
    {
        if (!isStarted)
        {
            _rigidbody2D.simulated = false;
            return;
        }
        
        // _rigidbody2D.AddForce(Vector2.down*speed);
        // transform.Translate(Vector3.down * speed * Mathf.Lerp(0, 1, Time.deltaTime));
    }

    void Init()
    {
        transform.position = Vector3.up * 1.5f;
        isStarted = true;
        _rigidbody2D.simulated = isStarted;
        _rigidbody2D.velocity = Vector2.zero;
    }

    public void Restart()
    {
        Init();
    }

    private void OnCollisionEnter2D(Collision2D other)
    {
        Debug.Log($"OnCollision: {other.gameObject.name}");
        
        switch (other.gameObject.tag)
        {
            case "nail":
                bool isRight = GameManager.Instance.RandomHit();
                // anim.SetTrigger(isRight ? "hit_right" : "hit_left");
                force.x = isRight ? Math.Abs(force.x) : -Math.Abs(force.x); 
                _rigidbody2D.AddForce(force, ForceMode2D.Impulse);
                
                GameManager.Instance.PlaySound(Sound.HitNail);
                break;
            case "slot":
                GameManager.Instance.FallInSlot(other.gameObject);
                Init();
                isStarted = false;
                break;
        }
    }
}
